﻿using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wlog.Model;

namespace wlog.Shell.Storage.Blob
{
    public class BlobUpdateCommand : BlobStorageCommand
    {
        Action<BlobTransferProgressChangedEventArgs> onProgress;
        Action<AsyncCompletedEventArgs> onComplete;

        bool eventSetupConfigured = false;

        public BlobUpdateCommand()
            : this(false)
        {
        }
        public BlobUpdateCommand(bool asynchronous)
            : this(asynchronous, null)
        {

        }
        public BlobUpdateCommand(bool asynchronous, Action<BlobTransferProgressChangedEventArgs> onProgress)
            : this(asynchronous, onProgress, null)
        {

        }
        public BlobUpdateCommand(bool asynchronous, Action<BlobTransferProgressChangedEventArgs> onProgress, Action<AsyncCompletedEventArgs> onComplete)
        {
            async = asynchronous;
            TransferType = TransferTypeEnum.Upload;
            SetUpEvents(async);
        }
        void SetUpEvents(bool asyncOp)
        {
            if (async)
            {
                this.TransferProgressChanged += BlobUploadCommand_TransferProgressChanged;
                this.TransferCompleted += BlobUploadCommand_TransferCompleted;
                eventSetupConfigured = true;
            }
            else
            {
                eventSetupConfigured = false;
            }
        }

        void BlobUploadCommand_TransferProgressChanged(object sender, BlobTransferProgressChangedEventArgs e)
        {
            if (onProgress != null)
            {
                onProgress(e);
            }
        }

        void BlobUploadCommand_TransferCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (onComplete != null)
            {
                onComplete(e);
            }
        }
        public override void Setup(string[] args)
        {
            base.Setup(args);
            // This will also set up async  
            SetUpEvents(async);
            if (async)
            {
                if (onProgress == null)
                {
                    onProgress = new Action<BlobTransferProgressChangedEventArgs>((BlobTransferProgressChangedEventArgs arg) =>
                    {
                        Results.WriteLine("{0}%", arg.ProgressPercentage);
                        if (Working)
                        {
                            Console.ReadKey();
                        }
                    });

                }
                if (onComplete == null)
                {
                    onComplete = new Action<AsyncCompletedEventArgs>((AsyncCompletedEventArgs arg) =>
                    {
                        if (arg.Cancelled)
                        {
                            Results.WriteLine("Cancelled blob uploading {0}", blobName);
                        }
                        else if (arg.Error != null)
                        {
                            Results.WriteLine("Error uploading blob {0}, Message : {1} ", blobName, arg.Error.Message);
                        }
                        else
                        {
                            Results.WriteLine("Success uploading blob {0}", blobName);
                        }
                        Console.WriteLine("\r\n");
                    });
                }
            }
            base.CreateTask(() => { UploadTask(); });
        }

        public OutputChannel UploadTask()
        {
            try
            {
                CloudBlobClient blobAPI = GetBlobAccount();
                Results.WriteLine("Connected to: {0}", blobAPI.BaseUri);
                var root = blobAPI.GetContainerReference(containerName);
                if (!string.IsNullOrEmpty(blobName))
                {
                    Results.WriteLine("Lets Create a blob {0} on the Containers created: {1}", blobName, containerName);
                    var blob = root.GetBlockBlobReference(additionalCommands[K_OPTIONS.objectname]);
                    // I will choose it later from argument
                    blob.Properties.ContentType = mime;

                    // I am using a syncronous uploading here...


                    bool isThere = blob.Exists();
                    if (isThere)
                    {
                        Results.WriteLine("Blob exists: {0}", blobName);
                    }
                    else
                    {
                        Results.WriteLine("Blob does not exists: {0}", blobName);
                    }
                    Results.WriteLine("Uploading ... {0}", filePath);

                    if (async == false)
                    {
                        UploadSync(filePath, blob);
                        Results.WriteLine("Written to... {0}", blob.Uri.ToString());

                    }
                    else
                    {
                        //  UnComment this 
                        // this.WaitForCompletion = true;
                        UploadAsync(filePath, blob);

                    }
                }
            }
            catch (Exception azureEx)
            {
                Results.WriteLine("Error ccreating Blob {0} ", azureEx.Message);
            }
            return Results;
        }

        public override Task Execute()
        {
            var result = base.Execute();

            return result;
        }

    }
}
